package com.vue.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.vue.constant.MessageConstant;
import com.vue.context.BaseContext;
import com.vue.dto.*;
import com.vue.entity.Course;
import com.vue.entity.Student;
import com.vue.exception.*;
import com.vue.mapper.StudentMapper;
import com.vue.mapper.TeacherMapper;
import com.vue.entity.Teacher;
import com.vue.result.PageResult;
import com.vue.service.TeacherService;
import com.vue.vo.TeacherRegisterVO;
import com.vue.vo.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    /**
     * 教师登录
     * @param loginDTO
     * @return
     */
    public Teacher login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUsername(username);

        //1、根据用户名查询数据库中的数据
        Teacher teacher = teacherMapper.getTeacher(userInfoVO);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (teacher == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传过来的明文密码进行MD5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(teacher.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
//        if (user.getStatus() == StatusConstant.DISABLE) {
//            //账号被锁定
//            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
//        }

        //3、返回实体对象
        return teacher;
    }


    /**
     * 获取教师信息
     * @param userInfoDTO
     * @return
     */
    public Teacher getUserInfo(UserInfoVO userInfoDTO) {
        Long id = BaseContext.getCurrentId();
        userInfoDTO.setId(id);
        return teacherMapper.getTeacher(userInfoDTO);
    }

    /**
     * 课程分页查询
     * @param coursePageQueryDTO
     * @return
     */
    public PageResult coursePageQuery(CoursePageQueryDTO coursePageQueryDTO) {
        Long teacherId = BaseContext.getCurrentId();
        coursePageQueryDTO.setTeacherId(teacherId);
        PageHelper.startPage(coursePageQueryDTO.getPageNum(),coursePageQueryDTO.getPageSize());
        Page<Course> page = teacherMapper.coursePageQuery(coursePageQueryDTO);

        long total = page.getTotal();
        List<Course> records = page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 教师注册
     * @param teacherRegisterVO
     */
    public void register(TeacherRegisterVO teacherRegisterVO) {
        String name = teacherRegisterVO.getName();
        String phone = teacherRegisterVO.getPhone();
        String email = teacherRegisterVO.getEmail();

        if (name.isEmpty() || phone.isEmpty() || email.isEmpty()){
            throw new RegisterFailedException(MessageConstant.NOT_BE_NULL);
        }

        if (name.length() < 2 || name.length() > 15){
            throw new RegisterFailedException(MessageConstant.NAME_FORMAT_ERROR);
        }

        if (!Pattern.matches("^(1[3-9]\\d{9})$",phone)){
            throw new RegisterFailedException(MessageConstant.PHONE_FORMAT_ERROR);
        }

        if (!Pattern.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", email) || email.length()>25){
            throw new RegisterFailedException(MessageConstant.EMAIL_FORMAT_ERROR);
        }

        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherRegisterVO, teacher);
        teacherMapper.insert(teacher);
    }

    /**
     * 教师找回密码
     * @param forgetPasswordDTO
     */
    public void forgetPassword(NewPasswordDTO forgetPasswordDTO) {
        String username = forgetPasswordDTO.getUsername();
        String phone = forgetPasswordDTO.getPhone();
        String email = forgetPasswordDTO.getEmail();
        String password = forgetPasswordDTO.getNewPassword();
        String rePassword = forgetPasswordDTO.getRePassword();
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUsername(username);
        Teacher teacher = teacherMapper.getTeacher(userInfoVO);
        if (teacher == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!teacher.getPhone().equals(phone)){
            throw new AccountInfoErrorException(MessageConstant.PHONE_NOT_FOUND);
        }
        if (!teacher.getEmail().equals(email)){
            throw new AccountInfoErrorException(MessageConstant.EMIAL_NOT_FOUND);
        }
        if (!password.equals(rePassword) || password.length()<5 || password.length()>15){
            throw new PasswordErrorException(MessageConstant.NEW_PASSWORD_ERROR);
        }
        teacher.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        teacherMapper.update(teacher);
    }

    /**
     * 根据id删除学生
     * @param id
     */
    public void deleteById (Long id) {
        teacherMapper.deleteById(id);
    }

    /**
     * 教师分页查询
     * @param teacherPageQueryDTO
     * @return
     */
    public PageResult teacherPageQuery(TeacherPageQueryDTO teacherPageQueryDTO) {
        PageHelper.startPage(teacherPageQueryDTO.getPageNum(),teacherPageQueryDTO.getPageSize());
        Page<Teacher> page = teacherMapper.teacherPageQuery(teacherPageQueryDTO);

        long total = page.getTotal();
        List<Teacher> records = page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 添加教师
     * @param teacherDTO
     */
    public void add(TeacherDTO teacherDTO) {
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherDTO, teacher);
        teacherMapper.insert(teacher);
    }

    /**
     * 修改教师信息
     * @param teacherDTO
     */
    public void update(TeacherDTO teacherDTO) {
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherDTO, teacher);
        teacherMapper.update(teacher);
    }

    /**
     * 教师修改密码
     * @param newPwd
     */
    public void updatePwd(String newPwd) {
        Teacher teacher = new Teacher();
        Long id = BaseContext.getCurrentId();
        teacher.setId(id);
        teacher.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
        teacherMapper.update(teacher);
    }
}
